import { Application } from "egg";
import { create } from "lodash";

export default (app: Application) => {
  const { STRING, INTEGER, DATE, ENUM, TEXT } = app.Sequelize;

  const User = app.model.define(
    "User",
    {
      id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      name: {
        type: STRING(50),
        allowNull: false,
        comment: "用户姓名",
      },
      email: {
        type: STRING(100),
        allowNull: false,
        unique: true,
        comment: "邮箱",
      },
      password: {
        type: STRING(255),
        allowNull: false,
        comment: "密码",
      },
      wallet_address: {
        type: STRING(100),
        allowNull: true,
        comment: "钱包地址",
        unique: true,
      },
      role: {
        type: ENUM("user", "organization", "admin"),
        defaultValue: "user",
        comment: "用户角色",
      },
      avatar: {
        type: STRING(255),
        allowNull: true,
        comment: "头像",
      },
      phone: {
        type: STRING(20),
        allowNull: true,
        comment: "手机号",
      },
      bio: {
        type: TEXT,
        allowNull: true,
        comment: "个人简介",
      },
      is_verified: {
        type: INTEGER,
        defaultValue: 0,
        comment: "是否已验证",
      },
      status: {
        type: ENUM("active", "inactive", "banned"),
        defaultValue: "active",
        comment: "账户状态",
      },
      last_login_at: {
        type: DATE,
        allowNull: true,
        comment: "最后登录时间",
      },
      created_at: {
        type: DATE,
        allowNull: false,
        defaultValue: app.Sequelize.literal("CURRENT_TIMESTAMP"),
        comment: "创建时间",
      },
      updated_at: {
        type: DATE,
        allowNull: false,
        defaultValue: app.Sequelize.literal("CURRENT_TIMESTAMP"),
        comment: "更新时间",
      },
    },
    {
      tableName: "users",
      timestamps: true,
      paranoid: true, // 软删除
      underscored: true,
    }
  );

  // 关联关系
  User.associate = function (): void {
    // 用户可以有多个项目
    app.model.User.hasMany(app.model.Project, {
      foreignKey: "creatorId",
      as: "projects",
    });

    // 用户可以有多个捐款记录
    app.model.User.hasMany(app.model.Donation, {
      foreignKey: "donorId",
      as: "donations",
    });
  };

  return User;
};
